package com.zy.edu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.ClassinfoDao;
import com.zy.edu.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-07-13
 */
@Service
@Transactional
public class ClassinfoServiceImpl extends ServiceImpl<ClassinfoDao, Classinfo> implements ClassinfoService {

    @Resource
    UserService userService;

    @Resource
    UserClassService userClassService;

    @Resource
    CourseChapterClassService courseChapterClassService;

    @Resource
    CourseService courseService;
    @Override
    public Map saveOrUpdate(Classinfo classinfo, InputParam inputParam) {
        if(StringUtils.isEmpty(classinfo.getId())){
            User temp = userService.selectById(inputParam.getUserId());
            if(temp.getRoleType().equals(Role.AREA)){
                classinfo.setJurisId(temp.getJurisId());
            }
            if(temp.getRoleType().equals(Role.SCHOOL)){
                classinfo.setJurisId(temp.getJurisId());
                classinfo.setSchoolId(temp.getSchoolId());
            }

            classinfo.setId("c-"+UUID.randomUUID().toString().replaceAll("-",""));
            classinfo.setCreateTime(new Date());
            classinfo.setStatus(1);

            this.baseMapper.insert(classinfo);

            //关联老师
            if(!StringUtils.isEmpty(classinfo.getTeacherId())){
                addUserClass(classinfo);
            }

        }else{

            this.baseMapper.updateById(classinfo);
            userClassService.delete(new EntityWrapper<UserClass>()
                    .eq("cid", classinfo.getId()));
            if(!StringUtils.isEmpty(classinfo.getTeacherId())){
                addUserClass(classinfo);
            }

        }
        //更新静态数据
        SystemParam.CLASSINFOS.put(classinfo.getId(),classinfo.getName());
        return ResponseInfo.success(null);
    }

    private void addUserClass(Classinfo classinfo ){
        if(StringUtils.isEmpty(classinfo.getTeacherId())){ return ;}
        String[] tidArr = classinfo.getTeacherId().split(",");
        for (String s : tidArr) {
            if(s.length()>2) {
                UserClass uc = new UserClass();
                uc.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                uc.setUid(s);
                uc.setCid(classinfo.getId());
                userClassService.insert(uc);
            }
        }
    }

    @Override
    public Map list(Classinfo classinfo, InputParam inputParam) {
        //当前用户的信息
        User temp = userService.selectById(inputParam.getUserId());
        classinfo.setStatus(1);
        //区管用户，只能查询区里的班级
        if(temp.getRoleType().equals(Role.AREA)){
            classinfo.setJurisId(temp.getJurisId());
        }else if(temp.getRoleType().equals(Role.SCHOOL)){
            classinfo.setSchoolId(temp.getSchoolId());
        }else if(temp.getRoleType().equals(Role.TEACHER)){
            classinfo.setId(temp.getId());
        }

        //前端查询传入的 学校与辖区数据
        if(!StringUtils.isEmpty(inputParam.getJurisId())){
            classinfo.setJurisId(inputParam.getJurisId());
        }
        if(!StringUtils.isEmpty(inputParam.getSchoolId())){
            classinfo.setSchoolId(inputParam.getSchoolId());
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        //查分页
        if(inputParam!=null && inputParam.getPage()!=null && inputParam.getSize()!=null
                && inputParam.getPage()>0 &&  inputParam.getSize()>0){
            Page<Classinfo> page=new Page<>(inputParam.getPage(),inputParam.getSize());
            if(temp.getRoleType().equals(Role.TEACHER)){
                //老师的班级管理特殊处理，只能查询自己已经关联的班级
                page.setRecords(this.baseMapper.listPageByTeachId(page, classinfo));
                resultMap.put("rows", page.getRecords());
            }else {
                //为了分页，先查所有班级
                page.setRecords(this.baseMapper.listPage(page, classinfo));
                List<Classinfo> listTemp = page.getRecords();
                //要为每个班级查出老师
                for (Classinfo clsTemp : listTemp) {
                    clsTemp.setTeacherList(userService.getTeaByClsId(clsTemp.getId()));
                }
                resultMap.put("rows", listTemp);
            }

            resultMap.put("total", (int) page.getTotal());
            return ResponseInfo.success(resultMap);
        }else {
            return ResponseInfo.success(null);
        }

    }

    @Override
    public Map dele(Classinfo classinfo) {
        if(!StringUtils.isEmpty(classinfo.getId())){
            //设置为不可用
            classinfo.setStatus(0);
            this.baseMapper.updateById(classinfo);
            SystemParam.CLASSINFOS.remove(classinfo.getId());
            //删除学生
            InputParam inputParam = new InputParam();
            inputParam.setClassId(classinfo.getId());
            userService.deleByClsId(inputParam);
        }
        return ResponseInfo.success(null);
    }

    @Override
    public List<Classinfo> findByUserId(String userId) {
        if(!StringUtils.isEmpty(userId)){
            return this.baseMapper.findByUserId(userId);
        }
        return null;
    }

    /**
     * @Author: HuangHaiShui
     * @Description:根据班级的id，获取该班级的数据以及老师
     * @Date: 17:51 2021/7/17
     * @param classinfo:
     * @param inputParam:
     * @return: Map
     **/
    @Override
    public Map getById(Classinfo classinfo, InputParam inputParam) {
        if(StringUtils.isEmpty(classinfo.getId())) {
            return ResponseInfo.error("参数错误");
        }
        inputParam.setPage(1);
        inputParam.setSize(20);
        classinfo.setStatus(1);
        Map map = this.list(classinfo, inputParam);
        Map data = (HashMap)map.get("data");
        List list = (List<Classinfo>)data.get("rows");
        if(list.size()>0) {
            return ResponseInfo.success(list.get(0));
        }else {
            return ResponseInfo.success(null);
        }
    }

    @Override
    public Map getBySchoolId(String schoolId, String userId) {
        if(!StringUtils.isEmpty(schoolId)
                &&!StringUtils.isEmpty(userId)){
            Classinfo classinfo = new Classinfo();
            classinfo.setSchoolId(schoolId);
            InputParam inputParam = new InputParam();
            inputParam.setUserId(userId);
            inputParam.setPage(1);
            inputParam.setSize(40);
            Map res = this.list(classinfo, inputParam);
            Map listPage = (HashMap)res.get("data");
            return ResponseInfo.success(listPage.get("rows"));
        }else{
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
    }

    @Override
    public Map deleByJruisId(InputParam inputParam) {
        if(!StringUtils.isEmpty(inputParam.getJurisId())){
            inputParam.setStatus(0);
            this.baseMapper.deleByJruisId(inputParam);
            this.initSystemData();
            return ResponseInfo.success("");
        }else{
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
    }


    @Override
    public void initSystemData() {
        SystemParam.CLASSINFOS = new HashMap();
        List<Classinfo> classinfoList = this.selectList(new EntityWrapper<Classinfo>()
                .eq("status",1));
        for (Classinfo classinfo : classinfoList) {
            SystemParam.CLASSINFOS.put(classinfo.getId(),classinfo.getName());
        }
    }

    //班级关联课程
    @Override
    public Map associatedCourse(InputParam inputParam) throws Exception {
        return courseChapterClassService.associatedCourse(inputParam);
    }



    @Override
    public Map getCourseByClassId(InputParam inputParam) {
        return courseChapterClassService.getCourseByClassId(inputParam);
    }

    @Override
    public Map getAllCourseClassId(InputParam inputParam) {
        //先获取所有课程id
        Map map = courseChapterClassService.getCourseByClassId(inputParam);
        if(map.get("code").toString().equals("200")){
            String[] ids =( String[]) map.get("data");
            if(ids.length>0){
                List<Course> courseList = courseService.selectBatchIds(Arrays.asList(ids));
                return ResponseInfo.success(courseList);
            }else{
                return ResponseInfo.success(new ArrayList());
            }
        }else{
            return map;
        }
    }

    @Override
    public  List<Classinfo> getByParam(InputParam inputParam){
        EntityWrapper entityWrapper = new EntityWrapper<Classinfo>();
        if(!StringUtils.isEmpty(inputParam.getJurisId())) {
            entityWrapper.eq("juris_id", inputParam.getJurisId());
        }
        if(!StringUtils.isEmpty(inputParam.getSchoolId())) {
            entityWrapper.eq("school_id", inputParam.getSchoolId());
        }
        entityWrapper.eq("status",1);
        List list = this.baseMapper.selectList(entityWrapper);
        return list;
    }
}
